import { Rules } from "async-validator";

export const isValidUsername = (str: string) =>
  ["admin", "editor"].indexOf(str.trim()) >= 0;

export const isExternal = (path: string) =>
  /^(https?:|mailto:|tel:)/.test(path);

export const isArray = (arg: any) => {
  if (typeof Array.isArray === "undefined") {
    return Object.prototype.toString.call(arg) === "[object Array]";
  }
  return Array.isArray(arg);
};

export const isValidURL = (url: string) => {
  const reg = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/;
  return reg.test(url);
};

export const is8BitCaseNum = (val: string) => {
  // 判断值至少8位并包含大小写字母、数字
  const reg = /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,32}$/;
  return reg.test(val);
};

// const naem_patt = /^[0-9a-zA-Z_]{6,16}$/;
export const passwordValidator = ( //密码输入验证器
  rule: Rules,
  value: string,
  callback: (error?: string | string[] | Error) => void
) => {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else if (!is8BitCaseNum(value)) {
    callback(new Error("密码至少8位并包含大小写字母、数字"));
  } else {
    callback();
  }
};

export const accountValidator = ( //账号输入验证器
  rule: Rules,
  value: string,
  callback: (error?: string | string[] | Error) => void
) => {
  if (value === "") {
    callback(new Error("请输入账号"));
  } else if (value.length < 3) {
    callback(new Error("账号最小长度为3"));
  } else {
    callback();
  }
};
